package net.p2pcdn.controller;

import com.qc.bean.result.ResponseData;
import net.p2pcdn.user.domain.User;
import net.p2pcdn.user.domain.UserAccountChangeRecord;
import net.p2pcdn.user.service.UserAccountService;
import net.p2pcdn.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * @author zx
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserAccountService userAccountService;

    @PostMapping("/login")
    public ResponseData login(String username, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        SecurityUtils.getSubject().login(token);
        return ResponseData.success("ok");
    }

    @GetMapping("info")
    public ResponseData getUserDetails() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        return ResponseData.success(user);
    }

    @PostMapping("/logout")
    public ResponseData logout(HttpServletRequest request) {
        SecurityUtils.getSubject().logout();
        request.getSession().invalidate();
        return ResponseData.success("ok");
    }

    @GetMapping("q/roles")
    public ResponseData queryRoles() {
        return ResponseData.success(userService.findAllRoles());
    }

    @GetMapping("{id}/roles")
    public ResponseData queryRoles(@PathVariable("id") int userId) {
        return ResponseData.success(userService.getUserRoles(userId));
    }

    @GetMapping("role/{id}")
    public ResponseData getRole(@PathVariable("id") int roleId) {
        return ResponseData.success(userService.getRole(roleId));
    }

    @DeleteMapping("role/{id}")
    public ResponseData deleteRole(@PathVariable("id") int roleId) {
        userService.deleteRole(roleId);
        return ResponseData.success("ok");
    }

    @PostMapping("role/{id}")
    public ResponseData putRole(@PathVariable("id") int roleId, String code, String name) {
        userService.updateRole(roleId, code, name);
        return ResponseData.success("ok");
    }

    @PostMapping("role")
    public ResponseData saveRole(String code, String name) {
        userService.saveRole(code, name);
        return ResponseData.success("ok");
    }

    @PostMapping("removeRole")
    public ResponseData deleteRole(int userId, int roleId) {
        userService.removeUserRole(userId, roleId);
        return ResponseData.success("ok");
    }

    @PostMapping("update")
    public ResponseData updateUser(int userId, String email, String password, String roleIds, Boolean locked) {
        userService.updateUser(userId, email, password, roleIds, locked);
        return ResponseData.success("ok");
    }

    @DeleteMapping("{id}")
    public ResponseData deleteUser(@PathVariable("id") int userId) {
        userService.deleteUser(userId);
        return ResponseData.success("ok");
    }

    @GetMapping("/q/1")
    public ResponseData queryUsers(int start, int limit, String email, Boolean locked) {
        return ResponseData.success(userService.queryUsers(email, "ROLE_ADMIN,ROLE_SUPER_ADMIN", locked, start / limit + 1, limit));
    }

    @GetMapping("/q/2")
    public ResponseData queryVipUsers(int start, int limit, String email, Boolean locked) {
        return ResponseData.success(userService.queryUsers(email, "ROLE_CUSTOMER_ADMIN", locked, start / limit + 1, limit));
    }

    @PostMapping("email/register")
    public ResponseData sendRegisterEmailCode(String email) {
        userService.sendRegisterEmailCode(email);
        return ResponseData.success("ok");
    }

    @PostMapping("register")
    public ResponseData register(String email, String emailCode, String password) {
        return userService.register(email, emailCode, password);
    }

    @PostMapping("email/findpwd")
    public ResponseData sendForgetPasswordEmailCode(String email) {
        return userService.sendForgetPasswordEmailCode(email);
    }

    @PostMapping("forget")
    public ResponseData forgetPassword(String email, String emailCode, String password) {
        return userService.forgetPassword(email, emailCode, password);
    }


    @GetMapping("email/updatepwd")
    public ResponseData sendUpdatePasswordEmailCode() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        return userService.sendUpdatePasswordEmailCode(user.getId());
    }

    @PostMapping("updatepwd")
    public ResponseData updatePassword(String emailCode, String oldPassword, String password) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        return userService.updatePassword(user.getId(), emailCode, oldPassword, password);
    }

    /**
     * 管理员给客户从之余额
     *
     * @param userId
     * @param money
     * @param remark
     * @param free
     * @return
     */
    @PostMapping("chargeBalance")
    @RequiresRoles(value = {"ROLE_SUPER_ADMIN", "ROLE_ADMIN"}, logical = Logical.OR)
    public ResponseData updatePassword(int userId, BigDecimal money, String remark, boolean free) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        userAccountService.chargeBalance(user.getId(), userId, money, free ? UserAccountChangeRecord.BizType.FREE : UserAccountChangeRecord.BizType.OFF_LINE_PAY, remark);
        return ResponseData.success("ok");
    }

    @GetMapping("balance/flow")
    public ResponseData queryChangeRecords(int userId, int page, int size, String bizType) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return ResponseData.error("您会登录或会话已过期", 403);
        }
        return ResponseData.success(userAccountService.queryChangeRecords(null, userId, null, StringUtils.isNotBlank(bizType) ?
                        UserAccountChangeRecord.BizType.valueOf(bizType) : null
                , page, size));
    }
}
